package front.action;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.JSON;
import common.servlet.BaseServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 马泽朋
 * @version 1.0
 * @date 2019/10/20 17:21
 */
@WebServlet("/Verification.action")
public class Verification extends BaseServlet {

    private static final long serialVersionUID = 2942978557408962385L;

    public void generate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(130, 38);
        //获取生成的验证码
        String code = lineCaptcha.getCode();
        request.getSession().setAttribute("code", code);
        //图形验证码写出，可以写出到文件，也可以写出到流
        ServletOutputStream outputStream = response.getOutputStream();
        lineCaptcha.write(outputStream);
        //声明响应文件类型
        response.setContentType("image/gif;charset=utf-8");
        outputStream.close();
    }
    public void verify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //拿到服务器端生成的验证码
        String code = (String) request.getSession().getAttribute("code");
        //拿到客户端输入的验证码
        String code1 = request.getParameter("code");
        PrintWriter writer = response.getWriter();
        Map<String,Object> map = new HashMap<>();
        System.out.println(code+">>>>"+code1);
        map.put("code", "-1");
        if (code.equalsIgnoreCase(code1)){
            map.put("code", "0");
        }
        writer.println(JSON.toJSONString(map));
        writer.close();
    }


}
